#include "BudgetManager.h"
#include <iostream>
#include <limits>

void displayMenu() {
    std::cout << "\n╔════════════════════════════════════════╗" << std::endl;
    std::cout << "║      个人账单管理系统 v2.0             ║" << std::endl;
    std::cout << "╚════════════════════════════════════════╝" << std::endl;
    std::cout << "【记录管理】" << std::endl;
    std::cout << "1.  记录收入" << std::endl;
    std::cout << "2.  记录支出" << std::endl;
    std::cout << "【查询功能】" << std::endl;
    std::cout << "3.  查看所有记录" << std::endl;
    std::cout << "4.  查看收入记录" << std::endl;
    std::cout << "5.  查看支出记录" << std::endl;
    std::cout << "6.  按类别查询" << std::endl;
    std::cout << "7.  按日期范围查询" << std::endl;
    std::cout << "8.  按金额范围查询" << std::endl;
    std::cout << "9.  按关键词搜索" << std::endl;
    std::cout << "10. 查看最近N条记录" << std::endl;
    std::cout << "11. 按日期排序查看" << std::endl;
    std::cout << "12. 按金额排序查看" << std::endl;
    std::cout << "【统计分析】" << std::endl;
    std::cout << "13. 按类别统计" << std::endl;
    std::cout << "14. 月度统计（含预算对比）" << std::endl;
    std::cout << "15. 财务总览" << std::endl;
    std::cout << "【预算管理】" << std::endl;
    std::cout << "16. 设置月度预算" << std::endl;
    std::cout << "17. 设置类别预算" << std::endl;
    std::cout << "18. 查看所有预算" << std::endl;
    std::cout << "19. 查看预算执行情况" << std::endl;
    std::cout << "20. 查看类别预算状态" << std::endl;
    std::cout << "21. 删除预算" << std::endl;
    std::cout << "0.  退出系统" << std::endl;
    std::cout << "────────────────────────────────────────" << std::endl;
    std::cout << "请选择操作 (0-21): ";
}

void clearInputBuffer() {
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

void addIncomeMenu(BudgetManager& manager) {
    std::string date, category, note;
    double amount;

    std::cout << "\n--- 记录收入 ---" << std::endl;
    std::cout << "日期 (YYYY-MM-DD): ";
    std::cin >> date;

    std::cout << "金额: ";
    while (!(std::cin >> amount)) {
        std::cout << "输入无效，请输入数字: ";
        clearInputBuffer();
    }

    clearInputBuffer();
    std::cout << "类别 (如: 工资/奖金/投资收益等): ";
    std::getline(std::cin, category);

    std::cout << "备注: ";
    std::getline(std::cin, note);

    manager.addIncome(date, amount, category, note);
}

void addExpenseMenu(BudgetManager& manager) {
    std::string date, category, note;
    double amount;

    std::cout << "\n--- 记录支出 ---" << std::endl;
    std::cout << "日期 (YYYY-MM-DD): ";
    std::cin >> date;

    std::cout << "金额: ";
    while (!(std::cin >> amount)) {
        std::cout << "输入无效，请输入数字: ";
        clearInputBuffer();
    }

    clearInputBuffer();
    std::cout << "类别 (如: 餐饮/交通/购物/娱乐等): ";
    std::getline(std::cin, category);

    std::cout << "备注: ";
    std::getline(std::cin, note);

    manager.addExpense(date, amount, category, note);
}

void queryByCategoryMenu(BudgetManager& manager) {
    std::string category;
    std::cout << "\n请输入要查询的类别: ";
    clearInputBuffer();
    std::getline(std::cin, category);
    manager.displayByCategory(category);
}

void queryByDateRangeMenu(BudgetManager& manager) {
    std::string startDate, endDate;
    std::cout << "\n请输入起始日期 (YYYY-MM-DD): ";
    std::cin >> startDate;
    std::cout << "请输入结束日期 (YYYY-MM-DD): ";
    std::cin >> endDate;
    manager.displayByDateRange(startDate, endDate);
}

void monthlyStatisticsMenu(BudgetManager& manager) {
    std::string yearMonth;
    std::cout << "\n请输入年月 (YYYY-MM): ";
    std::cin >> yearMonth;
    manager.displayMonthlyStatistics(yearMonth);
}

void queryByAmountRangeMenu(BudgetManager& manager) {
    double minAmount, maxAmount;
    std::cout << "\n请输入最小金额: ";
    while (!(std::cin >> minAmount)) {
        std::cout << "输入无效，请输入数字: ";
        clearInputBuffer();
    }
    std::cout << "请输入最大金额: ";
    while (!(std::cin >> maxAmount)) {
        std::cout << "输入无效，请输入数字: ";
        clearInputBuffer();
    }
    manager.displayByAmountRange(minAmount, maxAmount);
}

void searchByNoteMenu(BudgetManager& manager) {
    std::string keyword;
    std::cout << "\n请输入要搜索的关键词: ";
    clearInputBuffer();
    std::getline(std::cin, keyword);
    manager.searchByNote(keyword);
}

void displayRecentMenu(BudgetManager& manager) {
    int count;
    std::cout << "\n请输入要查看的记录数: ";
    while (!(std::cin >> count) || count <= 0) {
        std::cout << "输入无效，请输入正整数: ";
        clearInputBuffer();
    }
    manager.displayRecentTransactions(count);
}

void sortByDateMenu(BudgetManager& manager) {
    int choice;
    std::cout << "\n排序方式：" << std::endl;
    std::cout << "1. 按日期升序" << std::endl;
    std::cout << "2. 按日期降序" << std::endl;
    std::cout << "请选择 (1-2): ";
    while (!(std::cin >> choice) || (choice != 1 && choice != 2)) {
        std::cout << "输入无效，请输入 1 或 2: ";
        clearInputBuffer();
    }
    manager.displayAllTransactionsSortedByDate(choice == 1);
}

void sortByAmountMenu(BudgetManager& manager) {
    int choice;
    std::cout << "\n排序方式：" << std::endl;
    std::cout << "1. 按金额升序" << std::endl;
    std::cout << "2. 按金额降序" << std::endl;
    std::cout << "请选择 (1-2): ";
    while (!(std::cin >> choice) || (choice != 1 && choice != 2)) {
        std::cout << "输入无效，请输入 1 或 2: ";
        clearInputBuffer();
    }
    manager.displayAllTransactionsSortedByAmount(choice == 1);
}

void setMonthlyBudgetMenu(BudgetManager& manager) {
    std::string yearMonth;
    double amount;
    std::cout << "\n--- 设置月度预算 ---" << std::endl;
    std::cout << "年月 (YYYY-MM): ";
    std::cin >> yearMonth;
    std::cout << "预算金额: ";
    while (!(std::cin >> amount)) {
        std::cout << "输入无效，请输入数字: ";
        clearInputBuffer();
    }
    manager.getBudget().setMonthlyBudget(yearMonth, amount);
}

void setCategoryBudgetMenu(BudgetManager& manager) {
    std::string category;
    double amount;
    std::cout << "\n--- 设置类别预算 ---" << std::endl;
    std::cout << "类别名称: ";
    clearInputBuffer();
    std::getline(std::cin, category);
    std::cout << "预算金额: ";
    while (!(std::cin >> amount)) {
        std::cout << "输入无效，请输入数字: ";
        clearInputBuffer();
    }
    manager.getBudget().setCategoryBudget(category, amount);
}

void displayBudgetsMenu(BudgetManager& manager) {
    manager.getBudget().displayAllBudgets();
}

void displayBudgetStatusMenu(BudgetManager& manager) {
    std::string yearMonth;
    std::cout << "\n请输入年月 (YYYY-MM): ";
    std::cin >> yearMonth;
    manager.displayBudgetStatus(yearMonth);
}

void displayCategoryBudgetStatusMenu(BudgetManager& manager) {
    manager.displayCategoryBudgetStatus();
}

void deleteBudgetMenu(BudgetManager& manager) {
    int choice;
    std::cout << "\n--- 删除预算 ---" << std::endl;
    std::cout << "1. 删除月度预算" << std::endl;
    std::cout << "2. 删除类别预算" << std::endl;
    std::cout << "请选择 (1-2): ";
    while (!(std::cin >> choice) || (choice != 1 && choice != 2)) {
        std::cout << "输入无效，请输入 1 或 2: ";
        clearInputBuffer();
    }

    if (choice == 1) {
        std::string yearMonth;
        std::cout << "请输入要删除的年月 (YYYY-MM): ";
        std::cin >> yearMonth;
        manager.getBudget().removeMonthlyBudget(yearMonth);
    } else {
        std::string category;
        std::cout << "请输入要删除的类别: ";
        clearInputBuffer();
        std::getline(std::cin, category);
        manager.getBudget().removeCategoryBudget(category);
    }
}

void displayOverview(BudgetManager& manager) {
    std::cout << "\n========== 财务总览 ==========" << std::endl;
    std::cout << "总记录数: " << manager.getTransactionCount() << std::endl;
    std::cout << "总收入: " << std::fixed << std::setprecision(2) << manager.getTotalIncome() << std::endl;
    std::cout << "总支出: " << std::fixed << std::setprecision(2) << manager.getTotalExpense() << std::endl;
    std::cout << "净收入: " << std::fixed << std::setprecision(2) << manager.getNetIncome() << std::endl;
    std::cout << "================================" << std::endl;
}

int main() {
    BudgetManager manager;
    int choice;

    std::cout << "欢迎使用个人账单管理系统！" << std::endl;

    if (manager.getTransactionCount() > 0) {
        std::cout << "已加载 " << manager.getTransactionCount() << " 条历史记录。" << std::endl;
    }

    while (true) {
        displayMenu();

        while (!(std::cin >> choice)) {
            std::cout << "输入无效，请输入数字 (0-21): ";
            clearInputBuffer();
        }

        switch (choice) {
            case 1:
                addIncomeMenu(manager);
                break;
            case 2:
                addExpenseMenu(manager);
                break;
            case 3:
                manager.displayAllTransactions();
                break;
            case 4:
                manager.displayByType(TransactionType::INCOME);
                break;
            case 5:
                manager.displayByType(TransactionType::EXPENSE);
                break;
            case 6:
                queryByCategoryMenu(manager);
                break;
            case 7:
                queryByDateRangeMenu(manager);
                break;
            case 8:
                queryByAmountRangeMenu(manager);
                break;
            case 9:
                searchByNoteMenu(manager);
                break;
            case 10:
                displayRecentMenu(manager);
                break;
            case 11:
                sortByDateMenu(manager);
                break;
            case 12:
                sortByAmountMenu(manager);
                break;
            case 13:
                manager.displayStatisticsByCategory();
                break;
            case 14:
                monthlyStatisticsMenu(manager);
                break;
            case 15:
                displayOverview(manager);
                break;
            case 16:
                setMonthlyBudgetMenu(manager);
                break;
            case 17:
                setCategoryBudgetMenu(manager);
                break;
            case 18:
                displayBudgetsMenu(manager);
                break;
            case 19:
                displayBudgetStatusMenu(manager);
                break;
            case 20:
                displayCategoryBudgetStatusMenu(manager);
                break;
            case 21:
                deleteBudgetMenu(manager);
                break;
            case 0:
                std::cout << "\n感谢使用个人账单管理系统！再见！" << std::endl;
                return 0;
            default:
                std::cout << "\n无效的选择，请重新输入。" << std::endl;
        }
    }

    return 0;
}
